package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.baseadapter.listview.CommonAdapter;
import com.efounder.baseadapter.listview.ViewHolder;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.LoginFlowManager;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.AutoLineFeedLayout;
import com.utilcode.util.SizeUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 确认用户记录下助记词
 * Created by will on 18-4-26.
 */

public class TokenCheckActivity extends TCBaseActivity {
    private String mnemonic;
    private String number;
    private String userName;
    private GridView gridView;
    private MyTokenHelperAdapter gridAdapter;
    private List<String> mnemonics;
    private List<String> result_mnemonics = new ArrayList<>();
    private static final String PLACE_HOLDER = "place_holder";
    AutoLineFeedLayout alflMnemonicShow;

    private String address;
    private String ethPublicKey;
    private String ethPrivateKey;
    private String loginPwd = "";

    private TCAccountManager tcAccountManager;
    //钱包添加到服务器是否成功
    private boolean isAddWalletToServerSuccess = false;
    private AccountDao accountDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setEnableScreenShotListen(false);
        setContentView(R.layout.open_planet_activity_token_check);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.openplanet_verify_your_mnemic);
        accountDao = new AccountDao(this);
        mnemonic = getIntent().getExtras().getString("mnemonic");
        number = getIntent().getExtras().getString("number");
        userName = getIntent().getExtras().getString("userName");
        address = getIntent().getExtras().getString("address");
        ethPublicKey = getIntent().getExtras().getString("ethPublicKey");
        ethPrivateKey = getIntent().getExtras().getString("ethPrivateKey");
        loginPwd = getIntent().getStringExtra("loginPwd");


        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mnemonics = new ArrayList<>();
        parseMnemonic();
        result_mnemonics.add(PLACE_HOLDER);

        gridView = (GridView) findViewById(R.id.gv_token_helper);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridAdapter = new MyTokenHelperAdapter(this, R.layout.talk_chain_item_token_helper, result_mnemonics);
        gridView.setAdapter(gridAdapter);
        alflMnemonicShow = (AutoLineFeedLayout)
                findViewById(R.id.alfl_mnemonic_show);
        loadBottomView(false);

        Button tvNext = (Button) findViewById(R.id.tv_next);
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAddWalletToServerSuccess) {
                    //检查通讯密钥
                    checkMessageKey();
                } else {
                    //上传钱包
                    verifyResult();
                }

            }
        });
        tcAccountManager = new TCAccountManager(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing()){
            EFHttpRequest.cancelRequest(TAG);
        }
    }

    private void loadBottomView(boolean shuffle) {
//        if (shuffle) {
        Collections.shuffle(mnemonics);
        alflMnemonicShow.removeAllViews();
//        }

        for (int i = 0; i < mnemonics.size(); i++) {
            final LinearLayout linearLayout = new LinearLayout(this);
            final TextView textView = new TextView(this);
            textView.setPadding(SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5));
            textView.setBackgroundColor(getResources().getColor(R.color.op_float_window_color));
            textView.setTextColor(getResources().getColor(R.color.wechat_white_or_black));
            textView.setTextSize(COMPLEX_UNIT_DIP, 17);
            final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(SizeUtils.dp2px(10), SizeUtils.dp2px(5), SizeUtils.dp2px(10), SizeUtils.dp2px(5));
            textView.setText(mnemonics.get(i));
            textView.setLayoutParams(params);
            alflMnemonicShow.addView(linearLayout);
            linearLayout.addView(textView);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addTopView(linearLayout, textView.getText().toString());
                    loadBottomView(true);
                }
            });

        }
    }

    private void addTopView(final LinearLayout linearLayout, String text) {
        alflMnemonicShow.removeView(linearLayout);
//        final TextView textView1 = new TextView(linearLayout.getContext());
//        textView1.setPadding(SizeUtils.dp2px(5),SizeUtils.dp2px(5),SizeUtils.dp2px(5),SizeUtils.dp2px(5));
//        textView1.setBackgroundColor(getResources().getColor(R.color.op_orange_color));
//        textView1.setTextColor(getResources().getColor(R.color.op_text_white_color));
//        textView1.setTextSize(COMPLEX_UNIT_DIP,17);
//        textView1.setText(text);
        mnemonics.remove(text);
        if (result_mnemonics.size() == 1 && result_mnemonics.get(0).equals(PLACE_HOLDER)) {
            result_mnemonics.remove(0);
        }
        result_mnemonics.add(text);
        gridAdapter.notifyDataSetChanged();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (result_mnemonics.get(position).equals(PLACE_HOLDER)) {
                    return;
                }
                addBottomView(result_mnemonics.get(position));
            }
        });
//        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        params.setMargins(SizeUtils.dp2px(10),SizeUtils.dp2px(5),SizeUtils.dp2px(10),SizeUtils.dp2px(5));
//        textView1.setLayoutParams(params);
//
//        final LinearLayout linearLayout1 = new LinearLayout(linearLayout.getContext());
//        alflMnemonics.addView(linearLayout1);
//        linearLayout1.addView(textView1);
//        textView1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                addBottomView(linearLayout1, textView1.getText().toString());
//            }
//        });
    }

    private void addBottomView(String text) {
        final TextView textView1 = new TextView(TokenCheckActivity.this);
        textView1.setPadding(SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5));
        textView1.setBackgroundColor(getResources().getColor(R.color.op_float_window_color));
        textView1.setTextColor(getResources().getColor(R.color.wechat_white_or_black));
        textView1.setTextSize(COMPLEX_UNIT_DIP, 17);
        textView1.setText(text);
        mnemonics.add(text);
        result_mnemonics.remove(text);
        if (result_mnemonics.size() == 0) {
            result_mnemonics.add(PLACE_HOLDER);
        }
        gridAdapter.notifyDataSetChanged();
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(SizeUtils.dp2px(10), SizeUtils.dp2px(5), SizeUtils.dp2px(10), SizeUtils.dp2px(5));
        textView1.setLayoutParams(params);

        final LinearLayout linearLayout1 = new LinearLayout(TokenCheckActivity.this);
        alflMnemonicShow.addView(linearLayout1);
        linearLayout1.addView(textView1);
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTopView(linearLayout1, textView1.getText().toString());
                loadBottomView(true);
            }
        });
    }

    private void parseMnemonic() {
        String[] arr = mnemonic.split("\\s+");
        for (String ss : arr) {
            mnemonics.add(ss);
        }
    }

    /**
     * 验证助记词
     */
    private void verifyResult() {
        if (mnemonics.size() > 0 && result_mnemonics.size() > 0) {
            showDialog1(ResStringUtil.getString(R.string.openplanet_please_check_mnemonic));
            loadBottomView(true);
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String mnemonic : result_mnemonics) {
            stringBuilder.append(mnemonic).append(" ");
        }
        String result = stringBuilder.toString().trim();
        if (!mnemonic.equals(result)) {
            showDialog1(ResStringUtil.getString(R.string.openplanet_chech_zhujici));
            loadBottomView(true);
//            mnemonics.clear();
//            result_mnemonics.clear();
//            parseMnemonic();
//            loadBottomView(true);
//            alflMnemonics.removeAllViews();
//            alflMnemonics.addView(new TextView(this));
            return;
        }
        if (address == null || "".equals(address)) {
            showDialog1(ResStringUtil.getString(R.string.openplanet_tokencheck_text1));
            return;
        }
        showLoading(R.string.openplanet_tokencheck_isback);
        //todo 屏蔽上传子钱包20181019
//        tcAccountManager.addChildWallet(ethPublicKey, ethPrivateKey, address, "", "", IPAssetsConstant.ChainEnum.ETH
//                .chainName,null, new TCAccountManager.AccountManagerListener() {
//            @Override
//            public void onSuccess(Object object) {
//                isAddWalletToServerSuccess = true;
//                checkMessageKey();
//
//            }
//
//            @Override
//            public void onFail(String fail) {
//                dismissLoading();
//                ToastUtil.showToast(getApplicationContext(), R.string.openplanet_tokencheck_text2);
//            }
//        });

        isAddWalletToServerSuccess = true;
        checkMessageKey();

//        if (getIntent().hasExtra(CreateWalletActivity.LAST_ACTIVITY)) {
//            String lastActivity = getIntent().getStringExtra(CreateWalletActivity.LAST_ACTIVITY);
//            if ("myWallet".equals(lastActivity)) {
//                Intent intent1 = new Intent(TokenCheckActivity.this, MyWalletActivity.class);
//                ActivityCompat.finishAffinity(TokenCheckActivity.this);
//                return;
//            }
//
//        }

        //todo 2018、0509 生成 RSApublicKey
//        String[] s = RSAUtil.genKeyPair();
//        if (s == null) {
//            ToastUtil.showToast(TokenCheckActivity.this, "生成RSA密钥失败");
//            return;
//        }
//        String rsaPrivateKey = s[0];
//        String rsaPublicKey = s[1];
//
//        //保存
//        EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), rsaPrivateKey);
//        EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), rsaPublicKey);
        // sendToServer(address, ethPublicKey, rsaPublicKey);


    }

    /**
     * 检查通讯公钥
     */
    private void checkMessageKey() {
        showLoading(R.string.openplanet_tokencheck_isback);
        //新建成功后 检查通讯公钥
        tcAccountManager.checkAndUpdateMessageKey(EnvironmentVariable.getProperty(CHAT_USER_ID), true,
                new TCAccountManager.AccountManagerListener<String>() {
                    @Override
                    public void onSuccess(String rsaPublicKey) {
                        sendToServer(address, ethPublicKey, rsaPublicKey);
                    }

                    @Override
                    public void onFail(String fail) {
                        dismissLoading();
                        ToastUtil.showToast(getApplicationContext(), R.string.openplanet_tokencheck_text2);
                    }
                });
    }

    private void sendToServer(final String address, final String publicKey, String rsaPublicKey) {
        if (address == null || "".equals(address) || publicKey == null || "".equals(publicKey)) {
            showDialog1(ResStringUtil.getString(R.string.open_planet_recovering_fail_code_300));
            return;
        }
        if (rsaPublicKey == null || "".equals(rsaPublicKey)) {
            showDialog1(ResStringUtil.getString(R.string.open_planet_recovering_fail_code_301));
            return;
        }
        final HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        map.put("ethAddress", address);
        map.put("ethPublicKey", publicKey);
        map.put("comPublicKey", rsaPublicKey);
        map.put("needAddIntegral", "1");

        TCRequestUtil.postOAuthRequest(TAG, "user/updateUserEthPublicKeyAndAddress", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if (jsonObject.has("result")
                                    && jsonObject.getString("result")
                                    .equals("success")) {

                                //结束创建钱包的状态
                                EnvironmentVariable.setProperty(LoginFlowManager.getCreateWalletStateKey(number), "false");

                                recoverChildWallet(address);
//                                if (EnvironmentVariable.getProperty("old_user").equals("1")
//                                        && !EnvironmentVariable.getProperty(LoginFlowManager.getIsRegisterKey(number), "")
//                                        .equals("true")) {
//                                    Intent intent1 = new Intent(TokenCheckActivity.this, TabBottomActivityForTalkChain.class);
//                                    intent1.putExtra("mnemonic", mnemonic);
//                                    intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
//                                    TokenCheckActivity.this.startActivity(intent1);
//                                    ActivityCompat.finishAffinity(TokenCheckActivity.this);
//                                } else {
//                                    Intent intent = new Intent(TokenCheckActivity.this, SetupAvatarActivity.class);
//                                    intent.putExtra("userName", userName);
//                                    intent.putExtra("number", number);
//                                    startActivity(intent);
//                                }
                            } else {
                                dismissLoading();
                                EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
                                EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                                showDialog1(ResStringUtil.getString(R.string.openplanet_tokencheck_text3));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismissLoading();
                            EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
                            EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                            showDialog1(ResStringUtil.getString(R.string.openplanet_tokencheck_text3));
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                        EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
                        EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                        showDialog1(ResStringUtil.getString(R.string.openplanet_tokencheck_text3));

                    }
                });
    }


    //恢复子钱包
    private void recoverChildWallet(String mainAddress) {
        //恢复子账户之前 删除本地当前用户所有的子账户 避免影响
        tcAccountManager.restoreChildWallet(mainAddress, new TCAccountManager.AccountManagerListener<String>() {
            @Override
            public void onSuccess(String object) {
                //存入env
                EnvironmentVariable.setProperty("tc_ethAddress", address);
                EnvironmentVariable.setProperty("tc_ethPublicKey", ethPublicKey);

                //设置数据库中账户可用
                Account account = accountDao.getAccount(address);
                if (account != null) {
                    account.setEnable(true);
                    accountDao.update(account);
                }
                //通过主账户的助记词创建其他子账户
                Disposable disposable = tcAccountManager.createChildWalletByMnemonic(number, mnemonic)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                gotoNextPage();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                gotoNextPage();
                            }
                        });
                addDisposable(disposable);
            }

            @Override
            public void onFail(String fail) {
                if (isFinishing()||isDestroyed()){
                    return;
                }
                dismissLoading();
                new AlertDialog.Builder(TokenCheckActivity.this)
                        .setTitle(R.string.common_text_hint)
                        .setCancelable(false)
                        .setMessage(R.string.openplanet_tokencheck_text2)
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showLoading(R.string.openplanet_tokencheck_isback);
                                recoverChildWallet(address);
                            }
                        })
                        .create()
                        .show();
            }
        });

    }

    /**
     * 下一步跳转
     */
    private void gotoNextPage() {
        //跳转页面
        dismissLoading();
        if (EnvironmentVariable.getProperty("old_user").equals("1")
                && !EnvironmentVariable.getProperty(LoginFlowManager.getIsRegisterKey(number), "")
                .equals("true")) {
            Intent intent1 = new Intent(TokenCheckActivity.this, TabBottomActivityForTalkChain.class);
            intent1.putExtra("mnemonic", mnemonic);
            intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
            TokenCheckActivity.this.startActivity(intent1);
            ActivityCompat.finishAffinity(TokenCheckActivity.this);
        } else {
            Intent intent = new Intent(TokenCheckActivity.this, SetupAvatarActivity.class);
            intent.putExtra("userName", userName);
            intent.putExtra("number", number);
            startActivity(intent);
        }
    }

    public void showDialog1(String msg) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(msg)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tcAccountManager.getDisposable() != null) {
            tcAccountManager.getDisposable().dispose();
        }
    }

    public class MyTokenHelperAdapter extends CommonAdapter<String> {
        public MyTokenHelperAdapter(Context context, int layoutId, List<String> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder viewHolder, String item, int position) {
            if (item.equals(PLACE_HOLDER)) {
                viewHolder.setTextColor(R.id.tv_token_helper, getResources().getColor(R.color.transparent));
                viewHolder.setBackgroundColor(R.id.tv_token_helper, getResources().getColor(R.color.transparent));
            } else {
                viewHolder.setTextColor(R.id.tv_token_helper, getResources().getColor(R.color.op_text_white_color));
                viewHolder.setBackgroundRes(R.id.tv_token_helper, R.drawable.rectangle_bg_orange);
            }
            viewHolder.setText(R.id.tv_token_helper, position + 1 + "." + item);
        }
    }
}
